/**
 * www.mbaobao.com Inc.
 * Copyright (c) 2013 All Rights Reserved.
 */
package top.rushpeak.edu03.core.mq;

import java.util.List;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import top.rushpeak.edu03.core.exception.BusinessException;

/**
 *                       
 * @Filename MessageReceiver.java
 *
 * @Description 
 *
 * @Version 1.0
 *
 * @Author fred
 *
 * @Email kuci@mbaobao.com
 *       
 * @History
 *<li>Author: fred</li>
 *<li>Date: 2014-6-30</li>
 *<li>Version: 1.0</li>
 *<li>Content: create</li>
 *
 */
public class MessageReceiver implements MessageListener {
	
	private static final Logger				LOG		= Logger.getLogger(MessageReceiver.class);
	
	private static final Gson				gson	= new Gson();
	
	private List<HandMessageListener>	listeners;
	
	@Override
	public void onMessage(Message _message) {
		LOG.info("received message=" + _message);
		
		if (_message instanceof TextMessage) {
			onMessage((TextMessage) _message);
		} else if (_message instanceof ObjectMessage) {
			onMessage((ObjectMessage) _message);
		}
	}
	
	private void onMessage(TextMessage message) {
		if (LOG.isInfoEnabled()) {
			LOG.info("received message=" + message);
		}
		try {
			EventEnum type = EventEnum.getByCode(message.getStringProperty("type"));
			if (type == null) {
				throw new BusinessException("type不存在,type=" + type);
			}
			Map<String, String> data = gson.fromJson(message.getText(),
				new TypeToken<Map<String, String>>() {
				}.getType());
			
			for (HandMessageListener listener : listeners) {
				for (EventEnum event : listener.getActionEnum()) {
					if (event == type) {
						listener.onReceiveMessage(data);
					}
				}
			}
		} catch (Exception e) {
			LOG.error("", e);
		}
	}
	
	@SuppressWarnings("unchecked")
	private <T> void onMessage(ObjectMessage message) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("received message=" + message);
		}
		
		try {
			EventEnum type = EventEnum.getByCode(message.getStringProperty("type"));
			if (type == null) {
				throw new BusinessException("type不存在,type=" + type);
			}
			MessageContent<T> content = (MessageContent<T>) message.getObject();
			for (HandMessageListener listener : listeners) {
				for (EventEnum event : listener.getActionEnum()) {
					if (event == type) {
						listener.onReceiveMessage(content);
					}
				}
			}
		} catch (Exception e) {
			LOG.error("", e);
		}
		
	}
	
	public void setListeners(List<HandMessageListener> listeners) {
		this.listeners = listeners;
	}
	
}
